var $ = require('jquery');
var util = require('imutil');

var tpl = require('../tpl');
var i18n = require('../i18n');
var servant = require('../i18n/servant');
var bus = require('bus');

var defaults = {
	el: null,
	tmpl: tpl.contacts.search(servant.fuse({}, i18n.contacts))
};

var Search = function(config){
	this.config = util.extend({}, defaults, config);
	this.elems = {};
	
	this.__init();
    this.__initEvents();
};

Search.prototype = {
	__init: function(){
		this.elems.$el = $(this.config.el);
		this.elems.$search = $(this.config.tmpl);
		this.elems.$keywords = $('.J-im-keywords', this.elems.$search);
		this.elems.$delete = $('.J-im-icon-close', this.elems.$search);
        this.elems.$cancel = $('.J-im-cancel', this.elems.$search);

		this.elems.$el.append(this.elems.$search);
	},
	__initEvents: function(){
		var _this = this;



		this.elems.$keywords.focus(function(e){
			_this.focus();
		}).blur(function(){
            //setTimeout(_this.blur() ,500)
        }).bind('input', function(e){
            e.preventDefault();
            e.stopPropagation();
			_this.search(this.value);
		});

        this.elems.$delete.bind("click",function(e){
            e.preventDefault();
            _this.cleanSearchWord();
        })
        this.elems.$cancel.bind("click",function(){
            _this.cancelSearch();
        })
	},
	focus: function(){
        this.elems.$delete.css("display","block")
        this.elems.$search.addClass('im-search-on');
        bus.trigger('searchInputFocus');
	},
	blur: function(){
        //this.elems.$delete.css("display","none")
	},
	search: function(keyword){
		bus.trigger('searchContacts', keyword || this.elems.$keywords.val(), this.elems.$search);
	},
    cleanSearchWord:function(){
        this.blur();
        this.elems.$keywords.val("");
        bus.trigger('cleanSearchWord');
    },
    cancelSearch:function(){
        this.blur();
        this.elems.$keywords.val("");
        this.elems.$search.removeClass('im-search-on');
        bus.trigger('cancelSearch');
    }
};

module.exports = Search;